import datetime
import pyautogui
import pandas as pd
import re
from typing import Optional
from DrissionPage._units.listener import DataPacket
from zhipuai import ZhipuAI
from application.reply.reply import CommentReply


class CommentParser(object):
    def __init__(self, page):
        self.page = page
        self.aweme_id = None
        self.has_more = True
        self.comment_result = []
        self.ai_client = ZhipuAI(api_key="d30a6ff4270323ffd9a296814026bb85.Z4eqtU452FLIG6Cf")  # 填写您自己的APIKey
        self.filter_areas = False
        self.comment_div = None
        self.reply_engine = CommentReply(self.comment_div)

    def get_comment(self):
        video_running = True
        # 获取评论区元素
        self.comment_div = self.page.ele("tag:div@data-e2e=comment-list")
        while self.has_more:
            data_packet: DataPacket = self.page.listen.wait(timeout=10)
            if not data_packet:
                self.has_more = False
                break
            # 获取评论数据
            if data_packet.url.find('aweme/v1/web/comment/list') != -1:
                # 直接获取评论数据包
                comment_data = data_packet.response.body
                self.parse_comment(data=comment_data)

            # 向下滚动评论页面
            self.comment_div.scroll.to_bottom()

            if video_running:
                # 暂停视频
                # self.pause_video()
                print("暂停视频")
                video_running = False

    def parse_comment(self, data):
        """ 解析评论数据,返回是否还有下一页 """
        # 解析数据
        self.has_more = data['has_more'] > 0
        comments = data['comments']
        if not comments:
            return
        # for循环遍历，提取列表里的元素
        for info in comments:
            # 视频id
            aweme_id = info['aweme_id']
            # 评论id
            comment_id = info['cid']
            # 昵称
            nickname = info['user']['nickname']
            # 认证
            # custom_verify = info['user']['custom_verify']
            # 抖音号
            unique_id = info['user']['unique_id']
            # 标签
            signature = info['user']['signature']
            # 地区
            ip_label = info['ip_label']
            # 时间
            create_time = info['create_time']
            # 将时间戳转化为日期
            time = str(datetime.datetime.fromtimestamp(create_time))
            # 评论
            text = info['text']

            self.aweme_id = aweme_id
            row = {
                '视频id': aweme_id,
                '评论id': comment_id,
                '昵称': nickname,
                # '认证': custom_verify,
                '抖音号': unique_id,
                '标签': signature,
                '地区': ip_label,
                '时间': time,
                '评论': text,
                '分析': '待分析'
            }
            try:
                if self.filter_areas:
                    if row['地区'] in ['北京', '河北', '广州', '深圳']:
                        self.analysis(row)
                else:
                    self.analysis(row)
            except Exception as e:
                print(e)
            self.comment_result.append(row)

    def save(self, file_name) -> Optional[pd.DataFrame]:
        """ 保存评论数据到excel文件 """
        if not self.comment_result:
            return None
        df = pd.DataFrame(self.comment_result)
        df.to_excel(f"data\\{file_name}.xlsx", index=False)
        self.comment_result.clear()
        return df

    def analysis(self, row):
        pattern = r'\[.*?\]|{.*?}|\(.*?\)'  # 匹配小括号、中括号、大括号及其内容
        comment_text = re.sub(pattern, '', row['评论'])  # 替换匹配到的内容为空字符串
        if comment_text:
            response = self.ai_client.chat.completions.create(
                model="glm-4-flash",
                messages=[
                    {
                        "role": "system",
                        "content": "你是一个资深的信贷销售专员，分析语句是否有做贷款的需求，只回答是或否"
                    },
                    {
                        "role": "user",
                        "content": comment_text
                    }
                ],
                # top_p=0.7,
                # temperature=0.95,
                # max_tokens=1024,
                # tools=[{"type": "web_search", "web_search": {"search_result": True}}],
                # stream=False
            )

            row['分析'] = response.choices[0].message.content.strip()
            if '是' in row['分析']:
                self.reply_engine.comment_div = self.comment_div
                self.reply_engine.reply(row['评论'])
                print("回复消息")

    def pause_video(self):
        # 暂停视频
        all_windows = pyautogui.getAllWindows()
        for window in all_windows:
            if "抖音搜索" in window.title:
                window.activate()
                pyautogui.press('space')
